package org.yray.netty;
        import io.netty.buffer.ByteBuf;
        import io.netty.buffer.Unpooled;
        import io.netty.channel.Channel;
        import io.netty.channel.ChannelHandlerContext;
        import io.netty.channel.SimpleChannelInboundHandler;
        import io.netty.handler.codec.http.DefaultFullHttpResponse;
        import io.netty.handler.codec.http.FullHttpResponse;
        import io.netty.handler.codec.http.HttpHeaderNames;
        import io.netty.handler.codec.http.HttpObject;
        import io.netty.handler.codec.http.HttpRequest;
        import io.netty.handler.codec.http.HttpResponseStatus;
        import io.netty.handler.codec.http.HttpVersion;
        import io.netty.util.CharsetUtil;

/**
 * 自定义助手类
 * @author asus
 *
 */
public class MyHandler extends SimpleChannelInboundHandler<HttpObject>{

    //@Override
    protected void messageReceived(ChannelHandlerContext context, HttpObject msg)
            throws Exception {

        //通过context的上下文获取channel
        Channel channel = context.channel();

        if(msg instanceof HttpRequest){
            //获取请求地址
            System.out.println(channel.remoteAddress());
        }

        //自定义相应客户端信息
        ByteBuf content = Unpooled.copiedBuffer("hello neyy <<<>>>",CharsetUtil.UTF_8);

        //侯建httpResponse对象
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                content);

        //设置response对象的头信息
        response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());

        //将数据刷到客户端
        context.writeAndFlush(response);

    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {

    }
}

